package com.ds.dsm.config;

import com.ds.common.JDSException;
import com.ds.config.TreeListResultModel;
import com.ds.context.JDSActionContext;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.dsm.DSMFactory;
import com.ds.esd.util.TreePageUtil;
import com.ds.vfs.Folder;
import com.ds.vfs.ct.CtVfsFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Controller
@RequestMapping("/dsm/domain/config/")
public class AggDomainNavService {


    @RequestMapping(method = RequestMethod.POST, value = "domainNavConfig")
    @APIEventAnnotation(bindMenu = CustomMenuItem.loadChild)
    @ResponseBody
    public TreeListResultModel<List<AggDsmConfigTree>> getDomainNavConfig(String domainId) {
        TreeListResultModel<List<AggDsmConfigTree>> result = new TreeListResultModel<>();
        List<Folder> folderList = new ArrayList<>();
        try {
            Folder apiFolder = DSMFactory.getInstance().getAggregationManager().getApiClassConfigFolder();
            Folder rootfolder = CtVfsFactory.getCtVfsService().getFolderByPath(apiFolder.getPath() + domainId);
            for (Folder folder : rootfolder.getChildrenRecursivelyList()) {
                if (folder.getFileIdList().size() > 0) {
                    folderList.add(folder);
                }
            }
            Collections.sort(folderList, new Comparator<Folder>() {
                public int compare(Folder o1, Folder o2) {
                    return o1.getPath().compareTo(o2.getPath());
                }
            });

            JDSActionContext.getActionContext().getContext().put("parentPath", rootfolder.getPath());
            result = TreePageUtil.getTreeList(folderList, AggDsmConfigTree.class);
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return result;

    }


}
